package com.lottery.common.service.Impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lottery.common.contants.Constants;
import com.lottery.common.contants.ReQueryResult;
import com.lottery.common.contants.SequenceConstants;
import com.lottery.common.dao.CustomInfoMapper;
import com.lottery.common.dao.EventsInfoMapper;
import com.lottery.common.dao.MemberInfoMapper;
import com.lottery.common.dao.OrderInfoMapper;
import com.lottery.common.entity.*;
import com.lottery.common.service.CustomInfoService;
import com.lottery.common.service.OrderInfoService;
import com.lottery.common.service.SequenceService;
import com.lottery.common.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.nutz.lang.util.NutMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import static com.lottery.common.contants.Constants.*;

/**
 * <p>
 * 订单信息表 服务实现类
 * </p>
 *
 * @author jobob
 * @since 2019-09-23
 */
@Service
@Slf4j
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderInfoService {
    private ReQueryResult result = new ReQueryResult();
    @Resource
    private MemberInfoMapper memberInfoMapper;
    @Resource
    private OrderInfoMapper orderInfoMapper;
    @Resource
    private EventsInfoMapper eventsInfoMapper;
    @Resource
    private CustomInfoService customInfoService;
    @Resource
    private SequenceService sequenceService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public ReQueryResult synthesizeOrder(PaymentRecords records) {
        result = new ReQueryResult();
        result.success(SUCCESS_DESC);
        QueryWrapper<OrderInfo> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("order_num",records.getOrderNum());
        OrderInfo info=orderInfoMapper.selectOne(queryWrapper);
        if (info.getStatus()!=TYPE_TWO){
            result.error(Constants.ORDER_COMPLETED_ERROR);
            return result;
        }
        if (info.getOrderType()==TYPE_TWO){
            result=customOrder(info);
        }
        if (info.getOrderType()==TYPE_THREE){
            result=memberOrder(info);
        }
        if (info.getOrderType()==TYPE_FOUR){
            result=rechargeOrder(info);
        }
        if (result.getResultCode().equals(TYPE_ZERO_ZERO_STR)){
            OrderInfo orderInfo=new OrderInfo(info.getId(),TYPE_ZERO);
            orderInfoMapper.updateById(orderInfo);
            log.info("订单更新结束——已完成");
        }

        result.success(SUCCESS_DESC);
        return result;
    }

    public ReQueryResult customOrder(OrderInfo orderInfo){
        result = new ReQueryResult();
        String [] str=orderInfo.getTypeValue().split(",");
        List<CustomInfo> list=new ArrayList<>();
        MemberInfo memberInfo=getMemberBalance(orderInfo.getMemberId());
        for(String s:str){
            CustomInfo customInfo=new CustomInfo(memberInfo.getId(),s,new BigDecimal(RedisUtils.getConfigFromRedis(s, SysConfig.class).getValue()),
                    memberInfo.getPhone(),memberInfo.getEquipmentNum(),TYPE_ZERO);
            list.add(customInfo);
        }
        boolean flag=customInfoService.saveBatch(list);
        if (!flag){
            log.info("定制服务 添加失败");
            result.error(RECHARGE_FAIL);
            return result;
        }
        result.success(SUCCESS_DESC);
        return result;
    }

    /**
     * 会员充值订单
     * @return
     */
    public ReQueryResult memberOrder(OrderInfo orderInfo){
        result = new ReQueryResult();
        SysConfig sysConfig=RedisUtils.getConfigFromRedis(orderInfo.getTypeValue(),SysConfig.class);
        Calendar calendar = Calendar.getInstance();
        Date date=new Date();
        MemberInfo memberInfo=getMemberBalance(orderInfo.getMemberId());
        memberInfo.setExpiredCreateTime(date);
        if (memberInfo.getExpiredTime()!=null&&memberInfo.getExpiredTime().after(date)){
            date=memberInfo.getExpiredTime();
        }
        calendar.setTime(date);
        //会员延期 * 月
        calendar.add(Calendar.MONTH, Integer.valueOf(sysConfig.getRemark()));
        memberInfo.setExpiredTime(calendar.getTime());
        Integer count=memberInfoMapper.updateById(memberInfo);
        if (count<=0){
            log.info("会员充值 更新失败");
            result.error(RECHARGE_FAIL);
            return result;
        }
        NutMap nutMap= RedisUtils.getLoginInfo(memberInfo.getPhone());
        nutMap.setv("expiredTime",memberInfo.getExpiredTime());
        redisTemplate.opsForHash().put("loginMap",memberInfo.getPhone(), JSON.toJSONString(nutMap));

        result.success(SUCCESS_DESC);
        return result;
    }


    /**
     * 充值余额订单
     * @return
     */
    public ReQueryResult rechargeOrder(OrderInfo orderInfo){
        result = new ReQueryResult();
        MemberInfo memberInfo=getMemberBalance(orderInfo.getMemberId());
        memberInfo.setBalance(memberInfo.getBalance().add(orderInfo.getAmount()));
        Integer count=memberInfoMapper.updateById(memberInfo);
        if (count<=0){
            log.info("余额充值 更新失败");
            result.error(RECHARGE_FAIL);
            return result;
        }
        result.success(SUCCESS_DESC);
        return result;
    }



    public MemberInfo getMemberBalance(Long id){
        QueryWrapper<MemberInfo> queryWrapper=new QueryWrapper<>();
        queryWrapper.select("id","phone","equipment_num","balance","gold","expired_time");
        queryWrapper.eq("id",id);
        MemberInfo memberInfo=memberInfoMapper.selectOne(queryWrapper);
        return memberInfo;
    }


}
